<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        /*         setTimeout(function () {
                    console.log("timeout 2222");
                    alert("timeout 2222");
                }, 5000);
                setTimeout(function () {
                    console.log("timeout 1111");
                    alert("timeout 1111");
                }, 1000);
                function fn(){
                    console.log("fn");
                }
                fn();
        
                console.log("alert before");
                alert("-----"); //暂停程序执行
                console.log("alert after"); */
    </script>

    <input type="text" id="num">
    <button id="btn">计算</button>
    <script>
        //fibonacci数列
        function fibonacci(n) {
            //1 1 2 3 5 8 ...
            // f(n) = f(n - 1) + f(n - 2)
            return n <= 2 ? 1 : fibonacci(n - 1) + fibonacci(n - 2);
        }
        console.log(fibonacci(5));

        //factorial阶乘
        function factorial(n) {
            //n! = 1 * 2 * 3 * 4 * ... * (n - 2) *  (n - 1) * n
            return n <= 1 ? 1 : n * factorial(n - 1);
        }
        console.log(factorial(5));

        var input = document.getElementById("num");
        var btn = document.getElementById("btn");
        btn.onclick = function () {
            var num = input.value;
/*             let result = fibonacci(num);
            //复杂的计算可以交给分线程，计算的同时用户可以与界面交互
            console.log(result); */

            // new一个worker对象，传递新线程中执行的脚本url
            var worker = new Worker('js_worker.js');
            // 向分线程发送消息
            worker.postMessage(num);
            console.log("主线程向分线程发送数据 = " + num);
            // 绑定接收消息的监听
            worker.onmessage = function(event){
                console.log("主线程接收分线程返回的数据 = " + event.data);
            }
        }

    </script>
</body>

</html>